package com.ljp.makefriend.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 简易图形验证码工具
 */
public class CaptchaUtils {

    public static class CaptchaResult {
        private final String code;
        private final String base64;

        public CaptchaResult(String code, String base64) {
            this.code = code;
            this.base64 = base64;
        }

        public String getCode() {
            return code;
        }

        public String getBase64() {
            return base64;
        }
    }

    /**
     * 生成数字型验证码（PNG Base64 DataURL）
     * @param width  图片宽度
     * @param height 图片高度
     * @param length 验证码位数（建议 4-6）
     * @return 验证码结果，包含 code 与 base64
     */
    public static CaptchaResult generate(int width, int height, int length) {
        SecureRandom random = new SecureRandom();
        StringBuilder codeBuilder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            codeBuilder.append(random.nextInt(10));
        }
        String code = codeBuilder.toString();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 背景填充
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 干扰线
        for (int i = 0; i < 8; i++) {
            g.setColor(new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200)));
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        // 文本绘制
        g.setFont(new Font("Arial", Font.BOLD, height - 10));
        FontMetrics metrics = g.getFontMetrics();
        int charWidth = width / (length + 1);
        for (int i = 0; i < length; i++) {
            char ch = code.charAt(i);
            // 颜色与小幅度上下抖动
            g.setColor(new Color(20 + random.nextInt(120), 20 + random.nextInt(120), 20 + random.nextInt(120)));
            int x = (i + 1) * charWidth - metrics.charWidth(ch) / 2;
            int y = height - 10 - random.nextInt(6);
            g.drawString(String.valueOf(ch), x, y);
        }
        g.dispose();

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", baos);
            String base64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(baos.toByteArray());
            return new CaptchaResult(code, base64);
        } catch (Exception e) {
            throw new RuntimeException("生成验证码失败", e);
        }
    }
}